package org.cangku.controller;

import org.cangku.dao.PermissionDao;
import org.cangku.dao.RoleDao;
import org.cangku.dao.RolePermissionDao;
import org.cangku.entity.Permission;
import org.cangku.entity.Role;
import org.cangku.pojo.StateBean;
import org.cangku.pojo.permissionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;

    @RequestMapping("/query")
    @ResponseBody
    public List<Role> query(){
        return roleDao.getAllRole();
    }


    @RequestMapping("/dofenpei")
    @ResponseBody
    public List<permissionBean> doFenPei(int roleid){
        /*得到当前角色的所有权限*/
        List<Permission> listAll =  rolePermissionDao.queryByRoleid(roleid);
        /*获取根节点*/
        List<permissionBean> list = permissionDao.query(0);
        for(permissionBean pbean : list){
            int id = pbean.getId();
            /*查询子节点*/
            List<permissionBean> list1 = permissionDao.queryByParentid(id);
            StateBean stateBean = new StateBean();
            pbean.setState(stateBean);
            pbean.setNodes(list1);
        }

        /*回显当前角色所拥有的权限*/
        for(permissionBean pb : list){
            StateBean stateBean = new StateBean();
            for (Permission permission : listAll){
                if(pb.getId() == permission.getId()){
                    stateBean.setChecked(true);
                }
            }
            pb.setState(stateBean);
            /*得到子节点*/
            List<permissionBean> listSon = pb.getNodes();
            for(permissionBean pbn : listSon){
                StateBean stateBean1 = new StateBean();
                for (Permission permission : listAll){
                    if(pbn.getId() == permission.getId()){
                        stateBean1.setChecked(true);
                    }
                }
                pbn.setState(stateBean1);
            }
        }

        return list;
    }

    /*添加角色*/
    @RequestMapping("/insert")
    @ResponseBody
    public Map<String,Object> insert(Role role){
        Map<String,Object> map = new HashMap<String, Object>();

        roleDao.insert(role);
        List<Role> roleList = roleDao.getAllRole();
        map.put("rolelist",roleList);
        return map;
    }
}
